/*
 * Cache.h
*/

#ifndef CACHE_H_
#define CACHE_H_


#include <iostream>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
//   Creating a NODE Structure
struct rowt {
	string filename;
	string data;
	int time;
	struct rowt *next;
};

// Creating a class CACHE
class cachemem {
	struct rowt *front, *rear,*curr;
	int maxlength;
	int curlength;
public:
	cachemem() // constructure
	{
		front = rear = curr=NULL;
		maxlength=4;
		curlength=0;
	}
	void insert(string value, string data); // to insert an element
	string search(string fname); // to delete an element
	void show(); // to show the stack
};
// Insertion
void cachemem::insert(string value, string data) {

	struct rowt *ptr,*prev,*next;
	ptr = new rowt;
	ptr->filename = value;
	ptr->data = data;
	ptr->next = NULL;
	ptr->time=1;
	if (front == NULL){
		front = ptr;
		curlength++;
		front->time=1;
	}
	if(search(value).compare("NO")==0){
	if(curlength<maxlength){
		rear->next = ptr;
	rear = ptr;
	rear->time=1;
	curlength++;
	}
	if(curlength==maxlength){
		curr=front;
		int min=100000;
		while(curr){
			if(curr->time<min)
				min=curr->time;
			curr=curr->next;

		}
		curr=front;
		prev=curr;
		while(curr){
			next=curr->next;
			if(curr->time==min){
				prev->next=next;
				delete curr;
				break;
			}

					curr=curr->next;

				}
		curlength--;
		insert(value,data);


	}
	}
	else{
		struct rowt *temp;
			temp = front;
			while (1) {
				if (temp->filename.compare(value) == 0) {
					temp->data=data;
					temp->time=temp->time+1;

				}
				if (temp->next != NULL)
					temp = temp->next;
				else
					break;
			}
	}
}

//Search
string cachemem::search(string value) {
	string result = "";

	if (front == NULL) {
		cout<<"cache table is empty"<<endl;
		return "NO";
	}

	struct rowt *temp;
	temp = front;
	while (1) {
		if (temp->filename.compare(value) == 0) {
			result=temp->data;

		}
		if (temp->next != NULL)
			temp = temp->next;
		else
			break;
	}
	if(result.compare("")==0)
		result="NO";
	return result;

}

// Show Table
void cachemem::show() {
	struct rowt *ptr1 = front;
	if (front == NULL) {
		cout << "The table is empty!!";
		return;
	}
	cout << "\nThe table is\n";
	while (ptr1 != NULL) {
		cout << ptr1->filename << "|" << ptr1->data << " ->";
		ptr1 = ptr1->next;
	}
	cout << "END";
}



#endif /* CACHE_H_ */
